package com.horizon.common.controller;

import com.horizon.common.entity.IBaseEntity;
import com.horizon.common.repository.HQLInfo;
import com.horizon.common.service.IBaseService;
import com.horizon.common.util.IDGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Instant;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 通用控制器
 *
 * @author wangfuwei
 * @version 2018-08-09
 */
@Controller
public class CommonController {

    @Autowired
    private IBaseService<IBaseEntity> baseService;

    /**
     * 直接跳转视图
     *
     * @param request
     * @return
     */
    @RequestMapping("/view/**")
    public String view(HttpServletRequest request, Map<String, Object> map) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Iterator<Map.Entry<String, String[]>> iterator = parameterMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String[]> entry = iterator.next();
            String key = entry.getKey();
            String[] value = entry.getValue();
            if (value.length == 0) map.put(key, "");
            else if (value.length == 1) map.put(key, value[0]);
            else map.put(key, value);
        }
        return request.getRequestURI().replace("/view", "");
    }

    /**
     * 根据主键查询实体类信息
     *
     * @param fdId
     * @param className 实体类全路径
     * @return
     */
    @ResponseBody
    @RequestMapping("/info/{fdId}/{className}")
    public IBaseEntity info(@PathVariable("fdId") String fdId, @PathVariable("className") String className) throws Exception {
        Class entityClass = Class.forName(className);
        return baseService.find(entityClass, fdId);
    }

    /**
     * 根据属性查询实体类列表信息
     *
     * @param key       属性名称
     * @param value     属性值
     * @param className 实体类全路径
     * @return
     */
    @ResponseBody
    @RequestMapping("/info/{key}:{value}/{className}")
    public List<IBaseEntity> info(@PathVariable("key") String key, @PathVariable("value") String value, @PathVariable("className") String className) {
        HQLInfo hqlInfo = new HQLInfo(className);
        hqlInfo.setWhereBlock(key + " = :value");
        hqlInfo.setParameter("value", value);
        return baseService.findList(hqlInfo);
    }

    /**
     * 写入Cookie
     *
     * @param key    cookie的键
     * @param value  cookie的值
     * @param expiry 失效时间
     * @return
     */
    @ResponseBody
    @RequestMapping("/cookie/{key}:{value}/{expiry}")
    public Boolean cookie(HttpServletResponse response, @PathVariable("key") String key, @PathVariable("value") String value, @PathVariable("expiry") Integer expiry) {
        Cookie cookie = new Cookie(key, value);
        cookie.setPath("/");
        cookie.setMaxAge(expiry);
        response.addCookie(cookie);
        return true;
    }

    /**
     * 读取Cookie
     *
     * @param key cookie的键
     * @return
     */
    @ResponseBody
    @RequestMapping("/cookie/{key}")
    public String cookie(HttpServletRequest request, @PathVariable("key") String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(key)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    /**
     * 生成UUID
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/id")
    public String id() {
        return IDGenerator.generateID();
    }

    /**
     * 获取服务器时间戳
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/time")
    public Long time() {
        return Instant.now().toEpochMilli();
    }
}
